package com.samsung.sharepoint;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.wifi.WifiManager;
import android.net.wifi.WifiManager.MulticastLock;
import android.os.IBinder;
import android.os.Looper;
import android.util.Log;

public class listenService extends Service {

	private DatagramSocket socket;
	String data;
	private SharedPreferences spref;
	public static final String BROADCAST_ACTION = "com.samsung.sharepoint.ipbroadcast";
	private InetAddress myIP;

	@Override
	public void onCreate() {
		super.onCreate();
		Log.d("Sharepoint", "onCreate()");
		spref = getSharedPreferences("abc",MODE_PRIVATE);
		data =   spref.getString("name","Anonymous Pundit");
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
	
		 myIP = getLocalIpAddress();
		
		new Thread(new Runnable() {
			public void run() {
				Looper.prepareMainLooper(); // Provide Message queue for this thread
			
				WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
			   // Acquire a lock so as to avoid packet drop
				MulticastLock mcLock = wifiManager
						.createMulticastLock("mylock");
				mcLock.acquire();
				byte[] buf = new byte[1024];
				DatagramPacket packet = new DatagramPacket(buf, buf.length);
				try {
					socket = new DatagramSocket(4456); //Keep listening to udp messages
				} catch (SocketException e1) {
					e1.printStackTrace();
				}

			
				while (true) {
					try {
						while (true) {
							
							socket.receive(packet); 
							if (packet != null) { //If valid packet received
									String received = new String(packet.getData(), 0,
											packet.getLength()); 
									
									Intent intent = new Intent(BROADCAST_ACTION);
									
								    
									if(!packet.getAddress().equals(myIP)) { //If the packet received is not from "own" device
										intent.putExtra("IpAddress", packet.getAddress().toString());
										intent.putExtra("Sender",received);
										//Send broadcast message to receiver declared in "ChatList.java"
										// The broadacst message contains the sender's Ip Address, and his name
										sendBroadcast(intent);
									}
									DatagramPacket pack = new DatagramPacket(data
										.getBytes(), data.length(), packet
										.getAddress(), 4456);
									// Send packet back to the sender of udp broadcast message, the message includes its user name
									socket.send(pack);
							}
						}
					} catch (IOException e) {
						Log.d("LOLS", "IO Exce" + e.toString());
						e.printStackTrace();
					} catch (NullPointerException e) {
						Log.d("listenService", "NPE" + e.toString());
					}
				}
			}

		}).start();
		return 0;
	}

	// Get IpAddress for the device
	private InetAddress getLocalIpAddress() {
		try {
			for (Enumeration<NetworkInterface> en = NetworkInterface
					.getNetworkInterfaces(); en.hasMoreElements();) {
				NetworkInterface intf = en.nextElement();
				for (Enumeration<InetAddress> enumIpAddr = intf
						.getInetAddresses(); enumIpAddr
						.hasMoreElements();) {
					InetAddress inetAddress = enumIpAddr.nextElement();
					if (!inetAddress.isLoopbackAddress()) {
						return inetAddress;
						
					}

				}
			}
		} catch (SocketException ex) {
			Log.e("ServerActivity", ex.toString());
		}
		return null;
	}
	@Override
	public void onDestroy() {
		super.onDestroy();
	}

	@Override
	public IBinder onBind(Intent arg0) {
		return null;
	}

}
